import omit from './omit'
import { workTree } from './tree-array'
/**
 * 仅适用于el-table 行数据分组
 * @param {*} datas  Array数据
 * @param {*} groups  Array 分组字段
 * @returns Array
 * 
 * 例如: 
 * 原始数据：
 * [
    { a: 1, b: 2, c: 3, d: 4, name: '1x' },
    { a: 1, b: 2, c: 3, d: 4, name: '1a' },
    { a: 1, b: 2, c: 3, d: 4, name: '1d' },
    { a: 1, b: 3, c: 3, d: 4, name: '1a' }
   ]
 *   
 * 1. 首先转换成tree数据arrayGroupForElTable:
 * [
    {
        "a": 1,
        "_children": [
            {
                "b": 2,
                "_children": [
                    {
                        "a": 1,
                        "b": 2,
                        "c": 3,
                        "d": 4,
                        "name": "1x"
                    },
                    {
                        "a": 1,
                        "b": 2,
                        "c": 3,
                        "d": 4,
                        "name": "1a"
                    },
                    {
                        "a": 1,
                        "b": 2,
                        "b": 3,
                        "c": 3,
                        "d": 4,
                        "name": "1a"
                    }
                ],
                "rowSpan": 1
            }
        ],
        "rowSpan": 4
    }
    ]
 * 2. 再将tree数据转换成handlerGroupToEltable:
 * [
    {
        "a": 1,
        "b": 2,
        "c": 3,
        "d": 4,
        "name": "1x",
        "_rowSpans_": {
            "a": 4,
            "b": 3
        }
    },
    {
        "a": 1,
        "b": 2,
        "c": 3,
        "d": 4,
        "name": "1a",
        "_rowSpans_": {
            "a": 0,
            "b": 0
        }
    },
    {
        "a": 1,
        "c": 3,
        "d": 4,
        "name": "1a",
        "_rowSpans_": {
            "a": 0,
            "b": 1
        }
    }
    ]
 * 
 * 
 * @author xiufu.wang
 */

function arrayToTree(datas, pidField) {
    const res = {};
    const pids = [];

    let fields = [pidField]
    if (pidField.indexOf('&') > -1) {
        const r = pidField.split('&');
        if (r[0] && r[1]) {
            fields = [r[0], r[1]]
            datas = datas.map(r => {
                if (!(pidField in r)) {
                    r[pidField] = r[fields[0]] + '&' + r[fields[1]];
                }
                return r;
            })
        }
    }

    for (let i = 0; i < datas.length; i++) {
        const item = datas[i];
        const pid = item[pidField];
        if (!res[pid]) {
            pids.push(pid)
        }
        let addFields = {};
        if (fields.length > 1 && !res[pid]) {
            addFields = fields.reduce((m, f) => {
                m[f] = item[f];
                return m;
            }, {})
        }
        const chs = res[pid] || (res[pid] = { [pidField]: pid, _children: [], ...addFields })
        chs._children.push(item)
    }
    return pids.map(r => res[r])
}

//将数组转成tree结构
function arrayGroupForElTable(datas, groups, level) {
    level = level || 0
    const g = groups[level]
    if (level > groups.length - 1) {
        return null
    }
    let gdatas = arrayToTree(datas, g)
    gdatas.forEach((r, index) => {
        r.rowSpan = Math.max(1, r._children.length)
        if (level + 1 > groups.length - 1) {
            return null
        }
        r._children = arrayGroupForElTable(r._children, groups, level + 1, r)
    })
    return gdatas
}

// 将tree转换成数组(包含rowSpan数据)
function handlerGroupToEltable(datas, groups) {
    const groupResult = arrayGroupForElTable(datas, groups)
    const res = []
    function workTree(groupResult, rowSpans, level) {
        for (let i = 0; i < groupResult.length; i++) {
            const node = groupResult[i]
            // 分组最后一级节点
            if (groups.length - 1 < level) {
                const _rowSpans_ = {}
                groups.forEach((g) => {
                    if (i === 0) {
                        g.split('&').forEach((f) => {
                            _rowSpans_[f] = rowSpans[f];
                            rowSpans[f] = 0;
                        })
                        if(rowSpans[g] !== 0){
                            _rowSpans_[g] = rowSpans[g];
                        }
                        rowSpans[g] = 0
                    } else {
                        g.split('&').forEach((f) => {
                            _rowSpans_[f] = 0;
                        })
                        _rowSpans_[g] = 0
                    }
                })
                res.push({
                    ...node,
                    //新增数据ro
                    _rowSpans_: _rowSpans_
                })
            } else {
                const gname = groups[level]
                rowSpans = rowSpans || {}
                rowSpans[gname] = node.rowSpan;
                gname.split('&').forEach((f) => {
                    if (f) {
                        rowSpans[f] = node.rowSpan;
                    }
                });
                if (node._children) {
                    workTree(node._children, rowSpans, level + 1)
                }
            }
        }
    }
    workTree(groupResult, null, 0);
    console.log(res)
    return res
}

/**
 * 仅使用 pro-data-table
 * @param {*} datas 
 * @param {*} groups 
 * @returns 
 */
export default function (datas, groups) { //分组 字段
    if (!datas || !groups) {
        return datas
    }
    return handlerGroupToEltable(datas, groups)
}

/**
 * 仅使用pro-select-grouplist
 * [
 *  {group: '男', name: '张山'},
 *  {group: '男', name: '李四'},
 *  {group: '女', name: '张珊'}, 
 *  {group: '女', name: '李世'}
 * ]
 * => 
 * [
 *   {group: '男', _group_: true},
 *   {group: '男', name: '张山'},
 *   {group: '男', name: '李四'},
 *   {group: '女', _group_: true},
 *   {group: '女', name: '张珊'}, 
 *   {group: '女', name: '李世'}
 * ]
 */
export function arrayToGroupList(datas, group) {
    const res = { defaultOther: [] }
    const result = []
    workTree(datas, function (item) {
        const groupV = item[group] || 'defaultOther'
        if (!res[groupV]) {
            res[groupV] = []
            result.push({ _group_: groupV, children: res[groupV] })
        }
        res[groupV].push({ ...item })
    }, '_children_', null)
    if (res.defaultOther.length > 0) {
        result.push({
            _group_: '其他',
            children: res.defaultOther
        })
    }
    return result
}